// 实现promise初始化构造函数, 基本实现fulfilled,reject,then

// 思路： 首先因为promise 实例 是由 new 构造出来的，所以promise是一个类
// 其次控制Promise 异步是否完成是由  属性resolve,reject 来控制的， 其本质都是改变了Promise的状态 由 pending 准备状态到其他状态的改变。

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECT = 'reject'

class MyPromise1 {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }

    status = PENDING;

    value = null;

    reason = null;


    onFulfilledCallback = null;
    resolve = (value) => {
        if (this.status === PENDING) {
            this.status = FULFILLED;
            this.value = value;
        }
    }

    reject = (reason) => {
        if (this.status === PENDING) {
            this.status = REJECT;
            this.reason = reason;
        }
    }


    then(onFulfilled, onRejected) {

        if (this.status === FULFILLED) {
            onFulfilled(this.value)
        } else if (this.status == REJECT) {
            onRejected(this.reason);
        }
    }

}


// const promise = new MyPromise((resolve, reject) => {
//     reject('err')
//     resolve('success')

// })

// promise.then(value => {
//     console.log('resolve', value)
// }, reason => {
//     console.log('reject', reason)
// })

module.exports = MyPromise1